﻿using System.Windows;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;

namespace MSPToolkit.Behaviors
{
    public class WebBrowserHtmlPropertyBehavior : Behavior<WebBrowser>
    {
        public static readonly DependencyProperty HtmlProperty = DependencyProperty.Register("Html", typeof(string),
            typeof(WebBrowserHtmlPropertyBehavior), new PropertyMetadata(null, (obj, args) =>
                    {
                        var behavior = (WebBrowserHtmlPropertyBehavior)obj;
                        behavior.NavigateToString((string)args.NewValue);
                    }));

        public string Html
        {
            get { return (string)GetValue(HtmlProperty); }
            set { SetValue(HtmlProperty, value); }
        }

        private void NavigateToString(string html)
        {
            if (AssociatedObject != null && html != null)
                AssociatedObject.NavigateToString(html);
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.Loaded += AssociatedObjectLoaded;
        }

        void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
        {
            NavigateToString(Html);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.Loaded -= AssociatedObjectLoaded;
        }
    }
}